using System;
using System.Collections.Generic;
using System.Text;

namespace KeyboardImageViewer
{
	public class StringBag
	{
		private Dictionary<string, object> dictionary = new Dictionary<string, object>();

		public StringBag()
		{
		}

		public int Count
		{
			get
			{
				return dictionary.Count;
			}
		}

		public void Add(string item)
		{
			if (!this.dictionary.ContainsKey(item))
			{
				this.dictionary.Add(item, null);
			}
		}

		public void Remove(string item)
		{
			if (this.dictionary.ContainsKey(item))
			{
				this.dictionary.Remove(item);
			}
		}

		public bool Contains(string item)
		{
			return this.dictionary.ContainsKey(item);
		}

		public override string ToString()
		{
			StringBuilder sb = new StringBuilder();

			int addedTags = 0;
			foreach (string tag in this.dictionary.Keys)
			{
				if (!tag.Contains("|"))
				{
					sb.Append(tag.ToLowerInvariant());
				}

				addedTags++;
				if (addedTags < this.dictionary.Count)
				{
					sb.Append(", ");
				}
			}

			return sb.ToString();
		}

        public string ToPipeDelimitedList()
        {
            StringBuilder pipeStringBuilder = new StringBuilder();

            int addedTags = 0;

            foreach (string tag in this.dictionary.Keys)
            {
                if (!tag.Contains("|"))
                {
                    pipeStringBuilder.Append("|");
                    pipeStringBuilder.Append(tag.ToLowerInvariant());

                    addedTags++;
                }
            }

            if (addedTags > 0)
            {
                pipeStringBuilder.Append("|");
            }

            return pipeStringBuilder.ToString();
        }

		public static StringBag FromString(string tagString)
		{
			if (String.IsNullOrEmpty(tagString))
			{
				return null;
			}

			string[] tags = tagString.Split(new char[] { ',' });

			StringBag result = new StringBag();

			string trimTag;
			foreach (string tag in tags)
			{
				trimTag = tag.Trim();
				if (trimTag != "" && !trimTag.Contains("|"))
				{
					result.Add(trimTag.ToLowerInvariant());
				}
			}

			if (result.Count == 0)
			{
				return null;
			}

			return result;
		}
	}
}
